package com.itcast.activiti.utils;

import com.alibaba.fastjson.JSON;
import com.itcast.activiti.domain.AllowUserObj;
import com.itcast.activiti.service.IActIdUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ApproveUtils {

    @Autowired
    private IActIdUserService iActIdUserService;

    public boolean isAllow(String jsonStr, String userId, String deptId) {
        if (!StringUtils.hasText(jsonStr)) {
            return true;
        }
        List<AllowUserObj> userList = JSON.parseArray(jsonStr, AllowUserObj.class);

        //转化为  type（1：部门，2：用户） - ids数组 对象
        Map<String, List<String>> collect = userList.stream().collect(Collectors.groupingBy(
                p -> p.getObjectType(), Collectors.mapping(t -> t.getObjectId(), Collectors.toList())));

        //用户检测
        if (collect.get("2") != null && collect.get("2").contains(userId)) {
            return true;
        }

        //部门检测
        if (collect.get("1") != null) {
            for (String id : collect.get("1")) {
                List<String> list = iActIdUserService.getDepartmentsById(id);
                if (list.contains(deptId)) {
                    return true;
                }
            }
        }
        return false;
    }
}
